package com.demo.apparel.mapper.uniapp;

import com.demo.apparel.dto.PlatformDTO;
import com.demo.apparel.dto.PlatformVisitDTO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface PlatformVisitMapper {

    // 今日按 URI 聚合（返回每天每个 URI 的总和）
    @Select("SELECT uri, visit_date AS visitDate, SUM(daily_count) AS count " +
            "FROM platform_visit_daily " +
            "WHERE visit_date = CURDATE() " +
            "GROUP BY uri, visit_date")
    @Results({
            @Result(column = "uri", property = "uri"),
            @Result(column = "visitDate", property = "visitDate"),
            @Result(column = "count", property = "count")
    })
    List<PlatformVisitDTO> selectTodayVisit();

    // 今日每个平台明细（每行包含 uri）
    @Select("SELECT id, uri, platform AS platformName, visit_date AS visitDate, daily_count AS count " +
            "FROM platform_visit_daily " +
            "WHERE visit_date = CURDATE()")
    List<PlatformDTO> selectTodayVisitByPlatform();

    // 总访问量按 URI（汇总所有平台）
    @Select("SELECT uri, SUM(total_count) AS count " +
            "FROM platform_visit_total " +
            "GROUP BY uri")
    @Results({
            @Result(column = "uri", property = "uri"),
            @Result(column = "count", property = "count")
    })
    List<PlatformVisitDTO> selectTotalVisit();

    // 总访问量按平台明细（每行包含 uri）
    @Select("SELECT id, uri, platform AS platformName, total_count AS count " +
            "FROM platform_visit_total")
    List<PlatformDTO> selectTotalVisitByPlatform();

    // 更新总表（存在则 +1，不存在则插入）
    @Insert("INSERT INTO platform_visit_total (uri, platform, total_count, last_visit_time) " +
            "VALUES (#{uri}, #{platform}, 1, NOW()) " +
            "ON DUPLICATE KEY UPDATE total_count = total_count + 1, last_visit_time = NOW()")
    void incrementTotalVisit(@Param("uri") String uri, @Param("platform") String platform);

    // 更新当天表（存在则 +1，不存在则插入）
    @Insert("INSERT INTO platform_visit_daily (uri, platform, visit_date, daily_count) " +
            "VALUES (#{uri}, #{platform}, CURDATE(), 1) " +
            "ON DUPLICATE KEY UPDATE daily_count = daily_count + 1")
    void incrementDailyVisit(@Param("uri") String uri, @Param("platform") String platform);
}

